import dgram from 'node:dgram'
import { networkInterfaces } from 'node:os'
import 'colors'
import { 字串化 } from './_util.js'
import { 单机测试 } from './单机测试.js'

const 过滤接收 = address => !单机测试.是 && address === myAddress
export const myAddress = Object.values(networkInterfaces()).flat().find(_ => _.mac !== '00:00:00:00:00:00' && !_.internal && _.family === 'IPv4').address
const bcastAddr = myAddress.replace(/\d+$/, 2 ** 8 - 1) // '192.168.1.255'
const initPort = 8060
const listenPort = initPort + (!单机测试.是 ? 0 : 单机测试.端1 ? 0 : 1)
const remotePort = initPort + (!单机测试.是 ? 0 : 单机测试.端1 ? 1 : 0)
const client = dgram.createSocket({ type: 'udp4', reuseAddr: true })

client.on('close', () => {
  console.log('UDP 套接字已关闭')
})
client.on('error', err => {
  console.log(`UDP 套接字发生错误（因而关闭）:\n${err.stack}`)
  client.close()
})
client.on('listening', () => {
  console.log(`UDP 套接字开始监听（位于 ${myAddress}:${listenPort}）\n`)
})
client.on('message', function 转告(消息对象, { address, port }) {
  if (过滤接收(address)) return
  单机测试.是 && console.log(`\n\n${'-'.repeat(55)}\n${`UDP 套接字收到(经包装的)消息`.bgWhite}（来自 ${address}:${port}）：\n${消息对象}\n`)
  消息处理方案.执行?.(消息对象)
})
client.bind(listenPort)

export function 周知(消息对象) {
  client.send(字串化(消息对象), remotePort, bcastAddr)
}
export function 消息处理方案(回调) { 消息处理方案.执行 = 回调 }


// // 测试：
// setInterval(id => send(`My id: ${id}`), 2000, Math.floor(1000 * Math.random()))